## ---- Setup ----
## lmer estimation algorithm control
strict_tol <- lmerControl(optCtrl = list(xtol_abs = 1e-8,
                                         ftol_abs = 1e-8))


## ---- Data ----
load("dat/proc-data/soep_imp.RData")
soep_desc <- soep_imp$imputations$imp1 %>%
  filter(year == 2018) %>%
  dplyr::select(id, year, vote2017, vote_afd, cmr_arm, owner, weight) %>%
  dplyr::mutate(owner = factor(owner, levels = , c(0, 1), labels = c("Renters", "Owners"))) %>%
  dplyr::rename(
    Ownership = owner,
    `Voted AfD in 2017` = vote_afd,
    `Market Rents (EUR/sqm)` = `cmr_arm`
  ) %>%
  na.omit()

## ---- Rent plots ---
parties <- "AfD"
rent_vars <- "Market Rents (EUR/sqm)"
group_vars <- "Ownership"

for (party in parties) {
  for (rent_var in rent_vars) {
    for (group in group_vars) {
      x_range <- soep_desc %>% 
        filter(vote2017 != "None") %>%
        dplyr::select(all_of(rent_var)) %>% 
        range()
      
      num_groups <- soep_desc %>%
        filter(vote2017 != "None") %>%
        dplyr::select(all_of(group)) %>% 
        table() %>%
        length()
        
      
      plot_temp <- ggrent_plot(
        dat = soep_desc %>% 
          filter(vote2017 != "None") %>%
          mutate(!!paste0("Voted for ", party, " in 2017") := as.numeric(vote2017 == party)),
        x = rent_var,
        y = paste0("Voted for ", party, " in 2017"),
        group = group,
        weight = "weight",
        num_splines = 1L,
        heights = c(4, 2),
        xlim = x_range,
        font_size = 18L
      )
      
      ggsave(
        filename = make.names(paste0("ggrent_plot_", party, "_", rent_var, "_", group, ".pdf")),
        plot = plot_temp,
        path = "fig",
        width = 6 * num_groups,
        height = 9,
        dpi = 300,
        limitsize = FALSE
      )
    }
  }
}
